<!-- 车队编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="900"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="保险公司" prop="insurance_company_id">
        <el-select
          clearable
          v-model="form.insurance_company_id"
          placeholder="请选择报价的保险公司"
          filterable
          @change="handleInsuranceChange"
          style="width: 300px"
        >
          <el-option
            v-for="(item, index) in insuranceList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            @click="setInsurance(index)"
          >
            {{ item.title }}
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="业务员"
        prop="salesman"
        v-if="form.insurance_company_id != 0"
      >
        <el-input v-model="form.salesman" style="width: 120px" />
        <el-select
          style="width: 200px; margin-left: 8px"
          clearable
          v-model="form.salesman_id"
          placeholder="快速选择"
          filterable
        >
          <el-option label="直接填写或点击选择" :value="0"
            >直接填写或点击选择</el-option
          >
          <el-option
            v-for="(item, index) in insuranceSalesmanList"
            :key="item.id"
            :label="item.realname"
            :value="item.id"
            @click="setSalesman(index)"
          >
            {{ item.realname }}
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="返点" prop="rebate">
        <el-input v-model.number="form.rebate" style="width: 80px">
          <template #append>%</template>
        </el-input>
        <el-radio-group
          v-model="rebate"
          @change="quickSetRebate"
          style="margin-left: 8px"
        >
          <el-radio-button :label="25">25</el-radio-button>
          <el-radio-button :label="30">30</el-radio-button>
          <el-radio-button :label="35">35</el-radio-button>
          <el-radio-button :label="40">40</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商业险价格" prop="price">
        <el-input v-model="form.price" style="width: 120px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="起始时间" prop="s_time_date">
        <el-date-picker
          v-model="form.s_time_date"
          type="date"
          placeholder="起始日期"
          style="width: 130px"
          @change="selectStartDate"
          value-format="YYYY-MM-DD"
        />
        <el-input
          v-model.number="form.s_time_h"
          class="ml8"
          style="width: 80px"
        >
          <template #append>时</template>
        </el-input>
        <el-input
          v-model.number="form.s_time_i"
          class="ml8"
          style="width: 80px"
        >
          <template #append>分</template>
        </el-input>
      </el-form-item>
      <el-form-item label="结束时间" prop="e_time_date">
        <el-date-picker
          v-model="form.e_time_date"
          type="date"
          placeholder="结束日期"
          style="width: 130px"
          value-format="YYYY-MM-DD"
        />
        <el-input
          v-model.number="form.e_time_h"
          class="ml8"
          style="width: 80px"
        >
          <template #append>时</template>
        </el-input>
        <el-input
          v-model.number="form.e_time_i"
          class="ml8"
          style="width: 80px"
        >
          <template #append>分</template>
        </el-input>
      </el-form-item>
      <el-form-item label="参保项目" prop="items">
        <el-button :icon="Plus" style="margin-bottom: 16px" @click="addItems">
          新增项目
        </el-button>
        <ele-table border style="min-width: 580px; table-layout: fixed">
          <colgroup>
            <col />
            <col width="120px" />
            <col width="120px" />
          </colgroup>
          <thead>
            <tr>
              <th>参保项目</th>
              <th>保额</th>
              <th>价格</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in form.items" :key="row.key">
              <td>
                <el-input
                  clearable
                  v-model="row.title"
                  placeholder="参保项目"
                />
              </td>
              <td>
                <el-input clearable v-model="row.max_pay" placeholder="保额" />
              </td>
              <td>
                <el-input clearable v-model="row.price" placeholder="价格" />
              </td>
            </tr>
            <tr v-if="!form.items || !form.items.length">
              <td colspan="5" style="text-align: center; width: 100%">
                <ele-text style="padding: 4px 0" type="secondary">
                  暂无数据
                </ele-text>
              </td>
            </tr>
          </tbody>
        </ele-table>
      </el-form-item>

      <el-form-item label="报价图片" prop="pay_account">
        <image-upload :limit="10" v-model="form.images" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { Plus } from '@element-plus/icons-vue';
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import {
    updateInsurance,
    pageInsuranceCompanyList,
    pageInsuranceCompanySalesmanList
  } from '@/api/company';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    planId: {
      type: Number,
      default: 0
    },
    cate: String
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    plan_id: 0,
    vehicle_id: 0,
    trade_id: 0,
    insurance_company_id: '',
    insurance: '',
    salesman: '',
    salesman_id: 0,
    rebate: '',
    price: '',
    images: '',
    cate: '商业险',
    items: [],
    s_time_date: '',
    s_time_h: '',
    s_time_i: '',
    e_time_date: '',
    e_time_h: '',
    e_time_i: ''
  });

  const defaultItems = [
    {
      title: '',
      max_pay: '',
      price: ''
    }
  ];

  /** 表单验证规则 */
  const rules = reactive({
    insurance_company_id: [
      {
        required: true,
        message: '请选择保险公司',
        type: 'number',
        trigger: 'blur'
      }
    ],
    salesman: [
      {
        required: true,
        message: '请选择或者填写所属业务员',
        type: 'string',
        trigger: 'blur'
      }
    ],
    price: [
      {
        required: true,
        message: '请填写报价',
        type: 'string',
        trigger: 'blur'
      }
    ],
    rebate: [
      {
        required: true,
        message: '请填写返点',
        type: 'number',
        trigger: 'blur'
      }
    ],
    s_time_date: [
      {
        required: true,
        message: '请选择起始日期',
        type: 'string',
        trigger: 'blur'
      }
    ],
    e_time_date: [
      {
        required: true,
        message: '请选择结束日期',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      var requestData = Object.assign({}, form);
      requestData.items = JSON.stringify(requestData.items);
      updateInsurance(requestData)
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  /** 保险公司列表 */
  const insuranceList = ref([]);
  pageInsuranceCompanyList({ page: 1, limit: 99999999 })
    .then((res) => {
      insuranceList.value = res.list;
    })
    .catch((e) => {
      EleMessage.error(e.message);
    });

  /** 读取保险公司的业务员 */
  const insuranceSalesmanList = ref([]);
  const handleInsuranceChange = () => {
    pageInsuranceCompanySalesmanList({
      page: 1,
      limit: 99999999,
      insurance_company_id: form.insurance_company_id
    })
      .then((res) => {
        insuranceSalesmanList.value = res.list;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };
  const setInsurance = (i) => {
    form.insurance = insuranceList.value[i].title;
  };
  const setSalesman = (i) => {
    form.salesman = insuranceSalesmanList.value[i].realname;
  };

  /** 快速设置返点 */
  const rebate = ref(0);
  const quickSetRebate = () => {
    form.rebate = rebate.value;
  };

  /** 添加 */
  const addItems = () => {
    form.items.push({
      title: '',
      max_pay: '',
      price: ''
    });
  };

  const selectStartDate = () => {};
  const title = ref('');
  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.planId === 0) {
          assignFields({
            ...props.data
          });
        }

        rebate.value = '';
        form.plan_id = props.planId;
        form.vehicle_id = props.data.vehicle_id;
        form.trade_id = props.data.trade_id;
        title.value = props.data.plate_number + '的【商业险】报价';
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
